package com.upc.toss.slice;

import com.upc.toss.ResourceTable;
import com.upc.toss.SettingItem;
import com.upc.toss.SettingProvider;
import com.upc.toss.fraction.MainFraction;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventRunner;
import okhttp3.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChangeAbilitySlice extends AbilitySlice {

    Text text;
    int eqId;
    String eqName;
    ListContainer listContainer;
    ArrayList<SettingItem> list = new ArrayList<>();
    private SettingProvider provider;
    String username;

    Preferences preferences;
    DatabaseHelper databaseHelper;
//    MyEventHandler handler;

    Image imageAdd;
    protected void onStart(Intent intent) {
        username = intent.getStringParam("name");
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_change);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        listContainer.setItemProvider(provider);
        initListContainer();

        EventRunner runner = EventRunner.current();
//        handler = new ChangeAbilitySlice.MyEventHandler(runner);

        //username = intent.getStringParam("name");

        imageAdd = (Image) findComponentById(ResourceTable.Id_image_add);
        text = (Text) findComponentById(ResourceTable.Id_text_title) ;

        //list.

        imageAdd.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent1 = new Intent();
                intent1.setParam("name",username);
                present(new AddAbilitySlice(),intent1);
            }
        });
    }

    private void initListContainer() {
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        list = getData();
        SettingProvider settingProvider = new SettingProvider(list,this);
        listContainer.setItemProvider(settingProvider);

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                SettingItem item = (SettingItem) listContainer.getItemProvider().getItem(i);
                new ToastDialog(getContext())
                        .setText("你点击是:"+item.getEquipmentName())
                        // Toast显示在界面中间
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .show();
            }
        });

        listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                SettingItem item = (SettingItem) listContainer.getItemProvider().getItem(i);
//                new ToastDialog(getContext())
//                        .setText("长按事件点击:"+item.getEquipmentName())
//                        // Toast显示在界面中间
//                        .setAlignment(LayoutAlignment.BOTTOM)
//                        .show();
                return false;
            }
        });

    }

//    private ArrayList<SettingItem> addData(int id,String username,String equipmentTitle,String equipmentInfo){
//        list.add(new SettingItem(
//                1,
//                "root",
//                equipmentTitle,
//                ""
//        ));
//        return list;
//    }

    private ArrayList<SettingItem> getData() {
        list = new ArrayList<SettingItem>();
        GetEquipmentThread getEquipmentThread = new GetEquipmentThread();
        getEquipmentThread.start();
        while(getEquipmentThread.isAlive());

        return list;
    }

    public class GetEquipmentThread extends Thread{
        public void run(){
            try {
                String json = "{\"username\":\""+username+"\"}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://1.116.33.97:8080/getAllDevice")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=JSONObject.parseObject(responseData);

                int code=(int)jsonObject.get("code");
                if(code == 100){
                    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
                    JSONObject devices;
                    for(int i=0;i<jsonArray.size();i++){
//                        handler.sendEvent(1);
                        devices = (JSONObject) jsonArray.get(i);
                        list.add(i,new SettingItem(
                                devices.get("name").toString(),
                                devices.get("deviceId").toString()));
                    }
                }
                else{

                }
            }catch (Exception e){
                e.printStackTrace();

            }
        }
    }
    public void refresh() {
        list.clear();
        list = getData();
        provider = new SettingProvider(list,this);
        listContainer.setItemProvider(provider);
        provider.notifyDataChanged();
    }



//    private class MyEventHandler extends EventHandler {
//        private MyEventHandler(EventRunner runner) {
//            super(runner);
//        }
//        // 重写实现processEvent方法
//        @Override
//        public void processEvent(InnerEvent event) {
//            super.processEvent(event);
//            if (event == null) {
//                return;
//            }
//            int eventId = event.eventId;
//            switch (eventId) {
//                case 1:
//                    refresh();
//                    break;
//                default:
//                    break;
//            }
//        }
//    }
    @Override
    public void onActive() {
        super.onActive();
        refresh();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
